<template>
	<div class="layout-padding">
		<!-- <div class="layout-padding-auto layout-padding-view"> -->
		<div class="p-[10px] h-full overflow-y-auto">
			<!-- 基本信息 -->
			<div class="mb-4">
				<el-card>
					<template #header>
						<span class="text-primary">基本信息</span>
					</template>
					<div>
						<div class="w-full left">
							<el-row :gutter="24" class="mb20">
								<el-col :span="8" class="mb-4">
									<div class="flex">
										<div class="flexLeft">IMEI:</div>
										<div class="flex items-center flexRight flex-nowrap">
											<span class="whitespace-nowrap">{{ detailData?.imei }}</span>
											<el-button class="ml-1" icon="DocumentCopy" link type="primary" size="small" @click="copyText(detailData?.imei)"></el-button>
										</div>
									</div>
								</el-col>
								<el-col :span="8" class="mb-4">
									<div class="flex">
										<div class="flexLeft">IMEI别名:</div>
										<div class="flexRight">{{ detailData?.imeiAlias }}</div>
										<el-button size="small" class="ml-1" type="primary" @click="imeiAliasDialogRef.openDialog(detailData?.id, detailData?.imeiAlias)"
											>修改别名</el-button
										>
									</div>
								</el-col>
								<el-col :span="8" class="mb-4">
									<div class="flex">
										<div class="flexLeft">所属单位：</div>
										<div class="flexRight">{{ detailData?.deptName }}</div>
									</div>
								</el-col>
								<el-col :span="8" class="mb-4">
									<div class="flex">
										<div class="flexLeft">最近事件时间:</div>
										<div class="flexRight">{{ detailData?.recentEventTime }}</div>
									</div>
								</el-col>
								<el-col :span="8" class="mb-4">
									<div class="flex items-center">
										<div class="flexLeft">类型:</div>
										<div class="flexRight">{{ detailData?.deviceType }}</div>
									</div>
								</el-col>
								<el-col :span="8" class="mb-4">
									<div class="flex">
										<div class="flexLeft">设备型号:</div>
										<div class="flexRight">{{ detailData?.deviceModelName }}</div>
									</div>
								</el-col>
								<el-col :span="8" class="mb-4">
									<div class="flex items-center">
										<div class="flexLeft">设备状态:</div>
										<div class="flexRight">
											<div v-if="detailData.online === 20">
												<div v-if="detailData.deviceState === 20" class="text-primary">正常</div>
												<div v-if="detailData.deviceState === 30" class="text-warning">故障</div>
												<div v-if="detailData.deviceState === 40" class="text-error">报警</div>
											</div>
											<div v-else class="text-info">离线</div>
										</div>
									</div>
								</el-col>
								<el-col :span="8" class="mb-4">
									<div class="flex items-center">
										<div class="flexLeft">绑定状态:</div>
										<div class="flexRight">
											<el-tag v-if="detailData?.bindState === 10" type="info">未出库未绑定</el-tag>
											<el-tag v-if="detailData?.bindState === 20" type="info">出库未绑定</el-tag>
											<el-tag v-if="detailData?.bindState === 30" type="success">已绑定</el-tag>
										</div>
									</div>
								</el-col>
								<el-col :span="8" class="mb-4">
									<div class="flex items-center">
										<div class="flexLeft">设备使用状态:</div>
										<div class="flexRight">
											<el-tag v-if="detailData?.useState === 10" type="success">正常使用</el-tag>
											<el-tag v-if="detailData?.useState === 20" type="danger">设备手动停用</el-tag>
											<el-tag v-if="detailData?.useState === 30" type="warning">设备到期停用</el-tag>
										</div>
									</div>
								</el-col>
							</el-row>
						</div>
					</div>
				</el-card>
			</div>
			<!-- 安装信息 -->
			<div class="mb-4">
				<el-card>
					<template #header>
						<span class="text-primary">安装信息</span>
					</template>
					<div>
						<div class="left">
							<el-row :gutter="24" class="mb20">
								<el-col :span="8" class="mb-4">
									<div class="flex">
										<div class="flexLeft">安装位置:</div>
										<div class="flexRight">{{ detailData?.basicInstallLocation?.detailAddress }}</div>
									</div>
								</el-col>
								<el-col :span="8" class="mb-4">
									<div class="flex">
										<div class="flexLeft">首次安装时间:</div>
										<div class="flexRight">{{ detailData?.basicInstallLocation?.createTime }}</div>
									</div>
								</el-col>
								<el-col :span="8" class="mb-4">
									<div class="flex">
										<div class="flexLeft">建筑物:</div>
										<div class="flexRight">{{ detailData?.basicInstallLocation?.buildingName }}</div>
									</div>
								</el-col>
								<el-col :span="8" class="mb-4">
									<div class="flex">
										<div class="flexLeft">接警人员:</div>
										<div class="flexRight">{{ detailData?.basicInstallLocation?.alarmWorkerName }}</div>
									</div>
								</el-col>
								<el-col :span="8" class="mb-4">
									<div class="flex">
										<div class="flexLeft">楼层:</div>
										<div class="flexRight">{{ detailData?.basicInstallLocation?.floor }}</div>
									</div>
								</el-col>
								<el-col :span="8" class="mb-4">
									<div class="flex">
										<div class="flexLeft">经纬度:</div>
										<div class="flexRight">
											{{ detailData?.basicInstallLocation?.longitude }}
											<span>-</span>
											{{ detailData?.basicInstallLocation?.latitude }}
										</div>
									</div>
								</el-col>
								<el-col :span="8" class="mb-4">
									<div class="flex items-center">
										<div class="flexLeft">报警记录：</div>
										<div class="flexRight">
											<el-button link type="primary" @click="eventRecordDialogRef.openDialog(detailData?.imei)">查看 </el-button>
										</div>
									</div>
								</el-col>
								<el-col :span="8" class="mb-4">
									<div class="flex items-center">
										<div class="flexLeft">故障记录:</div>
										<div class="flexRight">
											<el-button link type="primary" @click="faultRecordDialogRef.openDialog(detailData?.imei)">查看 </el-button>
										</div>
									</div>
								</el-col>
							</el-row>
						</div>
					</div>
				</el-card>
			</div>
			<!-- 设备属性 -->
			<div class="mb-4" v-if="type === '1'">
				<div style="display: flex; justify-content: space-between">
					<div style="width: 20%">
						<el-card>
							<template #header>
								<span class="text-primary">设备仪表</span>
							</template>
							<div class="left" style="font-size: 12px; display: flex; justify-content: center; align-items: center">
								<el-row :gutter="20" class="mb20">
									<img src="https://rescommcdn.nbiotyun.com/res/kaiwan/ranqi/deviceType/RanqiBaojignqi-normal.png" alt="" />
								</el-row>
							</div>
						</el-card>
					</div>

					<div style="width: 80%; margin-left: 10px">
						<el-card>
							<template #header>
								<span class="text-primary">设备属性</span>
							</template>
							<div class="left">
								<el-row :gutter="20" style="margin-bottom: 20px; height: 150px">
									<el-col v-for="item in detailData?.realTimeData?.sensorTransmissionDataDetailsList" :key="item.id" :span="6" class="mb-2">
										<div
											class="p-[12px] bg-[#f1f1f1] border-[1px] border-[#f1f1f1] text-center rounded-[12px] h-[80px] cursor-pointer"
											:class="{
												'!border-primary': item.sensorTypeName === sensorTypeName,
											}"
											@click="getChartsData(item.gasTypeIdAndUnit, item.sensorTypeName)"
										>
											<div class="text-[16px]">{{ item.sensorTypeName }}</div>
											<div>
												<span class="text-[18px] font-semibold">{{ item.sensorVal }}</span>
												<span class="pl-1 text-xs">{{ item.sensorUnitName }}</span>
											</div>
										</div>
									</el-col>
								</el-row>
							</div>
						</el-card>
					</div>
				</div>
			</div>

			<!-- 曲线 -->
			<div class="mb-4" v-if="type === '1'">
				<el-card>
					<template #header>
						<div class="flex items-center justify-between">
							<span class="text-primary">{{ sensorTypeName }}</span>
							<el-button link :type="zoomLock ? 'primary' : 'info'" @click="handleScroll">{{ zoomLock ? '开启' : '关闭' }}调整曲线</el-button>
						</div>
					</template>
					<div class="left">
						<el-row :gutter="20" class="mb20">
							<div class="w-full h-[220px] min-h-[220px]">
								<LineChartHistory
									ref="LineChartHistoryRef"
									:seriesData="chartProps.seriesData"
									:xAxisData="chartProps.xAxisData"
									:zoomLock="zoomLock"
									:name="sensorTypeName"
								/>
							</div>
						</el-row>
					</div>
				</el-card>
			</div>
			<!-- 故障处理记录 -->
			<div class="mb-4" v-if="type === '2'">
				<el-card>
					<template #header>
						<div class="flex items-center justify-between">
							<span class="text-primary">故障处理记录</span>
							<el-button type="success" @click="handleComplete" v-if="alarmFaultSate === 20" :disabled="!processState?.dataList?.length"
								>完结工单</el-button
							>
						</div>
					</template>

					<el-table
						:data="processState.dataList"
						v-loading="processState.loading"
						border
						:cell-style="tableStyle.cellStyle"
						:header-cell-style="tableStyle.headerCellStyle"
						size="small"
						:height="360"
					>
						<el-table-column prop="remarks" label="反馈内容" show-overflow-tooltip min-width="180" />
						<el-table-column prop="annex" label="附件" show-overflow-tooltip min-width="150">
							<template #default="{ row }">
								<el-button type="primary" link :disabled="!row.annex" size="small" @click="handleDownFile(row.annex)">下载附件</el-button>
							</template>
						</el-table-column>
						<el-table-column prop="createBy" label="处理人" show-overflow-tooltip min-width="180" />
						<el-table-column prop="createTime" label="处理时间" show-overflow-tooltip min-width="180" />
					</el-table>
					<pagination small @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="processState.pagination" />
				</el-card>
			</div>
			<!-- 事件记录 -->
			<div v-if="type === '1'">
				<div class="flex items-start justify-between w-full">
					<el-row>
						<el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList2" size="small">
							<el-form-item label="" prop="createTime">
								<el-date-picker
									:end-placeholder="$t('syslog.inputEndPlaceholderTip')"
									:start-placeholder="$t('syslog.inputStartPlaceholderTip')"
									range-separator="To"
									type="datetimerange"
									v-model="state.queryForm.createTime"
									value-format="YYYY-MM-DD HH:mm:ss"
								/>
							</el-form-item>
							<el-form-item label="" prop="alarmEvenTypeCode">
								<el-select v-model="state.queryForm.alarmEvenTypeCode" filterable placeholder="请选择" :teleported="false" @change="handleChange">
									<el-option v-for="item in eventTypeOptions" :key="item.id" :label="item.eventTypeName" :value="item.eventTypeCode" />
								</el-select>
							</el-form-item>
							<el-form-item>
								<el-button icon="Search" type="primary" @click="getDataList2">{{ $t('common.queryBtn') }}</el-button>
								<el-button icon="Refresh" @click="resetQuery">{{ $t('common.resetBtn') }}</el-button>
							</el-form-item>
						</el-form>
					</el-row>
					<!-- <el-button size="small" @click="exportExcel">导出</el-button> -->
				</div>
				<el-table
					:data="state.dataList"
					v-loading="state.loading"
					border
					:cell-style="tableStyle.cellStyle"
					:header-cell-style="tableStyle.headerCellStyle"
					size="small"
					:height="320"
				>
					<el-table-column type="index" label="序号" width="60" />
					<el-table-column prop="receptionTime" label="事件时间" show-overflow-tooltip width="180" />
					<el-table-column prop="alarmEvenName" label="事件名称" show-overflow-tooltip width="150" />
					<el-table-column prop="sensorTransmissionDataDetailsList" label="设备上报内容" show-overflow-tooltip>
						<template #default="{ row }">
							<div class="flex items-center">
								<span
									v-for="(item, index) in row?.sensorTransmissionDataDetailsList"
									:key="item.sensorType"
									class="flex items-center mx-1 whitespace-nowrap flex-nowrap"
								>
									<span>{{ item.sensorTypeName }}</span>
									<span>：</span>
									<span>{{ item.sensorVal }}</span>
									<span v-if="row?.sensorTransmissionDataDetailsList?.length - 1 !== index" class="pr-1">,</span>
								</span>
							</div>
						</template>
					</el-table-column>
				</el-table>
				<pagination small @size-change="sizeChangeHandle2" @current-change="currentChangeHandle2" v-bind="state.pagination" />
			</div>
		</div>
		<!-- </div> -->
		<!-- 报警记录 -->
		<event-record-dialog ref="eventRecordDialogRef" />
		<!-- 故障记录 -->
		<fault-record-dialog ref="faultRecordDialogRef" />
		<!-- 修改别名 -->
		<imei-alias-dialog ref="imeiAliasDialogRef" @success="handlePutImei" />
	</div>
</template>
<script setup lang="ts">
import { getObj } from '/@/api/platform/basicDevice';
import { useRoute } from 'vue-router';
import { fetchRealTimeData, fetchRealTimeDataList, attributeCurve } from '/@/api/platform/realTimeData';
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchListAll as fetchEventTypeList } from '/@/api/alarm/alarmEventType';
import commonFunction from '/@/utils/commonFunction';
import { useMessageBox, useMessage } from '/@/hooks/message';
import { fetchList } from '/@/api/alarm/alarmFaultHandleLogging';
import other from '/@/utils/other';
import { putObj, getObj as getAlarmFaultObj } from '/@/api/alarm/alarmFaultLogging';
const EventRecordDialog = defineAsyncComponent(() => import('./components/eventRecord.vue'));
const faultRecordDialog = defineAsyncComponent(() => import('./components/faultRecord.vue'));
const LineChartHistory = defineAsyncComponent(() => import('./components/lineChart.vue'));
const ImeiAliasDialog = defineAsyncComponent(() => import('./components/imeiAlias.vue'));
// const selectedTab: any = ref('tab1');
const { copyText } = commonFunction();
const detailData: any = reactive({});
const eventRecordDialogRef = ref();
const faultRecordDialogRef = ref();
const imeiAliasDialogRef = ref();
const eventTypeOptions = ref<any[]>([]);
const queryRef = ref();
const zoomLock = ref(true);
const LineChartHistoryRef = ref();
const type = ref('');
const sensorTypeName = ref();
const alarmFaultSate = ref();
// charts data
const chartProps = reactive({
	xAxisData: [],
	seriesData: [],
});
// 清空搜索条件
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value?.resetFields();
	state.queryForm.alarmEventTypeName = '';
	// 清空多选
	getDataList2();
};
const state: BasicTableProps = reactive<BasicTableProps>({
	pageList: fetchRealTimeDataList,
	queryForm: {},
	dataList: [],
	loading: false,
	createdIsNeed: false,
});
const { getDataList: getDataList2, currentChangeHandle: currentChangeHandle2, sizeChangeHandle: sizeChangeHandle2 } = useTable(state);
const processState: BasicTableProps = reactive<BasicTableProps>({
	pageList: fetchList,
	loading: false,
	createdIsNeed: false,
	dataList: [],
	queryForm: {},
});
const { getDataList, currentChangeHandle, sizeChangeHandle, tableStyle } = useTable(processState);
// 查询报警记录
// const getEvenntDatalList = async () => {
// 	state.loading = true;
// 	fetchRealTimeDataList(state.queryForm)
// 		.then((res) => {
// 			state.dataList = res.data;
// 		})
// 		.finally(() => {
// 			state.loading = false;
// 		});
// };

const getDetail = () => {
	const { query } = useRoute();
	let id: string = query.id as string; //设备id
	type.value = query.type as string; //查看详情类型
	let fid = query?.fid as string; // 故障id
	id &&
		getObj(id).then((res) => {
			Object.assign(detailData, res.data);
			state.queryForm.imei = res.data.imei;
			fid && (processState.queryForm.alarmFaultLoggingId = fid);
			getRealTimeData(res.data.imei);
			getEventTypeList(res.data.deviceTypeId, res.data.deviceModelId);
			// getEvenntDatalList();
			getDataList2();
			fid && getAlarmFaultState(fid); // 查询故障状态
			fid && getDataList(); // 查询故障处理记录
		});
};
getDetail();
// 导出excel
// const exportExcel = () => {
// 	downBlobFile('/platform/basicDeviceEventRecord/export', Object.assign(state.queryForm), 'basicDeviceEventRecord.xlsx');
// };
// 请求故障详情信息
const getAlarmFaultState = (id: string) => {
	getAlarmFaultObj(id).then((res) => {
		alarmFaultSate.value = res.data.state;
	});
};
// 修改imei回调
const handlePutImei = (imeiAlias: string) => {
	detailData.imeiAlias = imeiAlias;
};
// 获取实时数据
const getRealTimeData = (imei: string) => {
	fetchRealTimeData(imei).then((res) => {
		detailData.realTimeData = res.data;
		if (res.data?.sensorTransmissionDataDetailsList?.length) {
			const l = res.data.sensorTransmissionDataDetailsList[0];
			getChartsData(l.gasTypeIdAndUnit, l.sensorTypeName);
		}
	});
};
// 获取事件类型
const getEventTypeList = (deviceTypeId: string, deviceModelId: string) => {
	fetchEventTypeList({ deviceModelId: deviceModelId, deviceTypeId: deviceTypeId, state: 20 }).then((res) => {
		eventTypeOptions.value = res.data;
	});
};
// 日期禁用
// const handleDisabledDate = (date: Date) => {
// 	const formatStr = `${new Date().getFullYear()}-new Date().getMonth()-1`;
// 	if (new Date(date).getTime() < new Date().getTime() || new Date(date).getTime() <script new Date(formatStr).getTime()) return false;
// 	return true;
// };
// 调整曲线
const handleScroll = () => {
	zoomLock.value = !zoomLock.value;
	LineChartHistoryRef.value.handleZoomLock(zoomLock.value);
};
// 完结工单
const handleComplete = async () => {
	try {
		await useMessageBox().confirm('确定完结工单吗？');
	} catch {
		return;
	}
	try {
		await putObj({ id: processState.queryForm.alarmFaultLoggingId, state: 10 });
		useMessage().success('操作成功！');
		getAlarmFaultState(processState.queryForm.alarmFaultLoggingId);
		getObj(detailData.id).then((res) => {
			Object.assign(detailData, res.data);
		});
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
// 请求传感器(属性)数据
const getChartsData = (gasTypeIdAndUnit: string, st: string) => {
	sensorTypeName.value = st;
	attributeCurve({ gasTypeIdAndUnit, imei: detailData?.imei }).then((res) => {
		chartProps.xAxisData = res.data.x;
		chartProps.seriesData = res.data.y;
	});
};
// 下载文件
const handleDownFile = (annex: string) => {
	other.downBlobFile(annex, {}, '');
};
const handleChange = (e: string) => {
	const item = eventTypeOptions.value.find((d) => d.eventTypeCode === e);
	state.queryForm.alarmEventTypeName = item.eventTypeName;
};
</script>
<style scoped lang="scss">
.flexLeft {
	text-wrap: nowrap;
	color: var(--el-color-info);
	margin-right: 4px;
}
</style>
